var crypto = require("crypto");

var express = require("express");
var router = express.Router();


var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });


var user = require("../model/user");
var essay = require("../model/essay");

router.get("/login", function(req, res) {
    res.render("login", { layout: "login", login: true });
});

router.get("/register", function(req, res) {
    res.render("login", { layout: "login", login: false });
});

router.post("/login", urlencodedParser, function(req, res) {
    var username = req.body.username;
    var password = req.body.password;
    var md5 = crypto.createHash("md5");
    md5.update(password);
    var sign = md5.digest("hex");
    user.find({ name: username, password: sign }, function(err, docs) {
        if (docs.length > 0) {
            req.session.islogin = true;
            req.session.name = username;
            req.session.userId = docs[0]._id;
            res.redirect("/editor");
        } else {
            res.send({ code: 0, status: -1, message: "登录失败" });
        }
    });
});

router.post("/register", urlencodedParser, function(req, res) {
    var username = req.body.username;
    var password = req.body.password;

    var md5 = crypto.createHash("md5");
    md5.update(password);
    var sign = md5.digest("hex");
    user.create({
            name: username,
            password: sign
        },
        function(err, doc) {
            res.redirect("/login");
        }
    );
});

module.exports = router;